<template>
  <div class="container">
    <h1 class="font-weight-100 text-center">哈基咪问卷系统</h1>
    <!-- 按钮组 -->
    <div class="mb-15">
      <el-button type="primary" :icon="Plus" @click="goToEditor">创建问卷</el-button>
      <el-button type="success" :icon="Compass" @click="goToComMarket">组件市场</el-button>
    </div>
    <!-- 数据表格 -->
    <el-table :data="tableData" style="width: 100%" border>
      <el-table-column
        fixed
        prop="createDate"
        label="创建日期"
        width="150"
        :formatter="formatDate"
      />
      <el-table-column prop="title" label="问卷标题" />
      <el-table-column prop="surveyCount" label="题目数" width="150" align="center" />
      <el-table-column prop="updateDate" label="最近更新日期" width="150" align="center" />
      <el-table-column fixed="right" label="操作" width="300" align="center">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="viewSurvey(scope.row)"
            >查看问卷</el-button
          >
          <el-button link type="primary" size="small" @click="editSurvey(scope.row)"
            >编辑</el-button
          >
          <el-button link type="primary" size="small" @click="deleteSurvey(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import { Plus, Compass } from '@element-plus/icons-vue'
import { ref } from 'vue'
// 引入路由
import { useRouter } from 'vue-router'
const router = useRouter()
// 类型引入
import { SurveyDBData, SurveyDBReturnData } from '@/types'
import { getAllSurvey, deleteSurveyById } from '@/db/operation'
// 工具方法
import { formatDate } from '@/utils'
const tableData = ref<SurveyDBData>([])

function getData() {
  getAllSurvey().then((res) => {
    tableData.value = res
  })
}
getData()
const goToEditor = () => {
  // 跳转的时候设置一下activeView
  localStorage.setItem('activeView', 'editor')
  router.push('/editor/survey-type')
}
const goToComMarket = () => {
  localStorage.setItem('activeView', 'materials')
  router.push('/materials')
}
// 预览问卷
const viewSurvey = (surveyInfo: SurveyDBReturnData) => {
  // console.log(surveyInfo.id)
  router.push({
    path: `/preview/${surveyInfo.id}`,
    state: {
      from: 'home',
    },
  })
}
// 编辑问卷
const editSurvey = (surveyInfo: SurveyDBReturnData) => {
  // console.log(surveyInfo.id)
  // 仅仅是做一个跳转，跳转到编辑器页面，但是需要将 id 带过去
  router.push(`/editor/${surveyInfo.id}/survey-type`)
}

// 删除问卷
const deleteSurvey = (surveyInfo: SurveyDBReturnData) => {
  deleteSurveyById(surveyInfo.id).then(() => {
    getData()
  })
}
</script>

<style scoped>
.container {
  padding: 20px;
}
</style>
